from typing import Any, List, Optional, TypeVar
from app.schemas.common import (
    BaseResponse, ListResponse, PaginationResponse,
    SuccessResponse, ErrorResponse
)

T = TypeVar('T')


def success(data: Optional[T] = None, message: str = "success") -> BaseResponse[T]:
    """成功响应"""
    # 如果数据是SQLAlchemy模型，确保它能被正确序列化
    if data and hasattr(data, '__dict__'):
        try:
            # 尝试转换为dict，如果失败则保持原样
            data_dict = data.__dict__.copy()
            # 移除SQLAlchemy特有的属性
            if '_sa_instance_state' in data_dict:
                del data_dict['_sa_instance_state']
            return BaseResponse(code=200, message=message, data=data_dict)
        except:
            pass
    return BaseResponse(code=200, message=message, data=data)


def success_list(data: List[T], message: str = "success") -> ListResponse[T]:
    """列表成功响应"""
    # 处理列表中的SQLAlchemy模型
    processed_data = []
    for item in data:
        if item and hasattr(item, '__dict__'):
            try:
                data_dict = item.__dict__.copy()
                if '_sa_instance_state' in data_dict:
                    del data_dict['_sa_instance_state']
                processed_data.append(data_dict)
            except:
                processed_data.append(item)
        else:
            processed_data.append(item)

    return ListResponse(code=200, message=message, data=processed_data)


def success_pagination(
    data: List[T],
    total: int,
    page_no: int = 1,
    page_size: int = 20,
    message: str = "success"
) -> BaseResponse[PaginationResponse[T]]:
    """分页成功响应"""
    # 处理列表中的SQLAlchemy模型
    processed_data = []
    for item in data:
        if item and hasattr(item, '__dict__'):
            try:
                data_dict = item.__dict__.copy()
                if '_sa_instance_state' in data_dict:
                    del data_dict['_sa_instance_state']
                processed_data.append(data_dict)
            except:
                processed_data.append(item)
        else:
            processed_data.append(item)

    total_pages = (total + page_size - 1) // page_size if total > 0 else 0

    # 创建分页数据对象
    pagination_data = PaginationResponse(
        items=processed_data,
        total=total,
        page=page_no,
        size=page_size,
        pages=total_pages
    )

    # 返回统一的响应格式
    return BaseResponse(code=200, message=message, data=pagination_data)


def success_action(message: str = "操作成功", data: Optional[dict] = None) -> SuccessResponse:
    """操作成功响应（无数据返回）"""
    return SuccessResponse(code=200, message=message, data=data)


def error(code: int = 400, message: str = "请求失败", data: Optional[dict] = None) -> ErrorResponse:
    """错误响应"""
    return ErrorResponse(code=code, message=message, data=data)


def not_found(message: str = "资源不存在") -> ErrorResponse:
    """404 错误响应"""
    return ErrorResponse(code=404, message=message)


def bad_request(message: str = "请求参数错误", data: Optional[dict] = None) -> ErrorResponse:
    """400 错误响应"""
    return ErrorResponse(code=400, message=message, data=data)


def unauthorized(message: str = "未授权访问") -> ErrorResponse:
    """401 错误响应"""
    return ErrorResponse(code=401, message=message)


def forbidden(message: str = "禁止访问") -> ErrorResponse:
    """403 错误响应"""
    return ErrorResponse(code=403, message=message)


def internal_error(message: str = "服务器内部错误") -> ErrorResponse:
    """500 错误响应"""
    return ErrorResponse(code=500, message=message)